<?php

namespace addons\member\utils;

/**
*
*/
class Coin {
    /**
     * 加密key
     * @var type
     */
    protected $apikey = 'DD896C5358CC23F43A3376B95A464C46';
    protected $api_url = 'http://161.117.252.229';
    /*
     * 生成比特地址
     */
    public function createBTCAddress()
    {
        set_time_limit(0);
        $postData['t'] = time();
        $postData['api_key'] = $this->apikey;
        $postData['sign'] = $this->makeSign($postData['t']);
        $url = $this->api_url.'/api/index/btcCreate';
        unset($postData['api_key']);
        $address = json_decode($this->posturl($url,$postData),true);
        if ($address['success'] == true){
            return authcode($address['data'],'DECODE',$this->apikey);
        }else{
            return false;
        }
    }
    /*
     * 创建以太地址
     */
    public function createEthAddress()
    {
        set_time_limit(0);
        $postData['t'] = time();
        $postData['api_key'] = $this->apikey;
        $postData['sign'] = $this->makeSign($postData['t']);
        unset($postData['api_key']);
        $url = $this->api_url.'/api/index/ethCreate';
        $data = json_decode($this->posturl($url,$postData),true);
        if ($data['success'] == true){
            $returnData['addr'] = authcode($data['data']['address'],'DECODE',$this->apikey);
            $returnData['pass'] = authcode($data['data']['pass'],'DECODE',$this->apikey);
            return $returnData;
        }else{
            return false;
        }
    }

    /**
     * 获取BTC交易记录
     */
    public function gettransaction(){
        $postData['t'] = time();
        $postData['api_key'] = $this->apikey;
        $postData['sign'] = $this->makeSign($postData['t']);
        unset($postData['api_key']);
        $url = $this->api_url.'/api/index/gettransaction';
        $data = json_decode($this->posturl($url,$postData),true);
        if(!empty($data['data'])){
            $memberM = new \addons\member\model\MemberAccountModel();
            $MemberBtcLog = new \addons\member\model\MemberBtcLog();
            $recordM = new \addons\member\model\TradingRecord();
            $BalanceM = new \addons\member\model\Balance();
            $coin_type = 2;
            foreach ($data['data'] as $key => $v) {
                $address = $v['address'];
                $user_id = $memberM->where('btc_address',$v['address'])->value('id');
                if(!$user_id) continue;
                $ex = $MemberBtcLog->getDetailByTxid($v['txid']);//订单匹配
                if($ex) continue;
                $amount = $v['amount'];
                if($amount<=0) continue;
                $BalanceM->startTrans();
                $re_balance = $BalanceM->updateBalance($user_id, $coin_type, $amount,1);
                if(!$re_balance){
                    $BalanceM->rollback();
                    continue;
                }
                $userRecord = $recordM->addRecord($user_id, $amount, $re_balance['before_amount'], $re_balance['amount'], $coin_type, 4, 1, 0, '外网转入');
                if(!$userRecord){
                    $BalanceM->rollback();
                    continue;
                }
                $val['user_id'] = $user_id;
                $val['amount'] = $amount;
                $val['sendingaddress'] = $address;
                if(isset($v['otheraccount'])) $val['referenceaddress'] = $v['otheraccount'];
                if(isset($v['blockhash'])) $val['block_hash'] = $v['blockhash'];
                else $val['block_hash'] = $v['txid'];
                $val['hash'] = $v['txid'];
                if(isset($v['fee'])) $val['fee'] = $v['fee'];
                else $val['fee'] = 0;
                $val['block_time'] = $v['timereceived'];
                $result = $MemberBtcLog->addLog($val);
                if(!$result){
                    $BalanceM->rollback();
                    continue;
                }
                $BalanceM->commit();
            }
        }
        // if ($data['success'] == true){
        //     $returnData['addr'] = authcode($data['data']['address'],'DECODE',$this->apikey);
        //     $returnData['pass'] = authcode($data['data']['pass'],'DECODE',$this->apikey);
        //     return $returnData;
        // }else{
        //     return false;
        // }
    }
    /*
     * 获取转入记录
     */
    public function getEthOrder($user_id)
    {
        $memberM  = new \addons\member\model\MemberAccountModel();
        $postData['t'] = time();
        $postData['api_key'] = $this->apikey;
        $postData['sign'] = $this->makeSign($postData['t']);
        $postData['user_id'] = $user_id;
        $postData['address'] = $memberM->where('id='.$user_id)->value('usdt_address');
        $url = $this->api_url.'/api/Eth/getEthOrders';
        $bool = $this->posturl($url,$postData);
        return $bool;
    }

    /*
     * 提现，自动转出
     */
    public function auto_withdraw($to_address,$amount)
    {
        $postData['t'] = time();
        // $postData['api_key'] = $this->apikey;
        $postData['sign'] = $this->makeSign($postData['t']);
        $postData['to_address'] = $to_address;
        $postData['value'] = $amount;
        $postData['type'] = 1;
        $postData['auto'] = authcode($amount,'ENCODE',$this->apikey,0);
        $postData['asign'] = strtoupper(md5($postData['t'].$this->apikey.$amount.$to_address.$postData['auto']));
        $url = $this->api_url.'/api/index/autoTrans';
        $ret = $this->posturl($url,$postData);
        return $ret;
    }
    /**
     * 生成签名
     */
    private function makeSign($time=false) {
        if($time){
            return strtoupper(md5($time.$this->apikey));
        }else{
            return strtoupper(md5(time().$this->apikey));
        }
    }

    private function posturl($url,$data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }


    public function getBtcOrders($user_id,$address = '',$coin_type=0){
        $cachekey = 'getBtcOrders'.$user_id;
        $redis = \think\Cache::connect(\think\Config::get('global_cache'));
        if($redis->get($cachekey)==1){
            return true;
        }
        $redis->set($cachekey,1,1);
        if(!$address) return false;
        if(!$coin_type) return false;
        $rand = rand(0,1);
        if($rand==0){
            $url = "https://blockchain.info/rawaddr/".$address;
            $sgdOrder = http($url,null,'get');
        }else{
            $postData['t'] = time();
            $postData['api_key'] = $this->apikey;
            $postData['sign'] = $this->makeSign($postData['t']);
            $postData['address'] = $address;
            $url = $this->api_url.'/api/Index/getBtcOrder';
            $sgdOrder = json_decode($this->posturl($url,$postData),1);
        }
        // dump($sgdOrder);exit();
        if($sgdOrder['success']){
            $MemberBtcLog = new \addons\member\model\MemberBtcLog();
            $recordM = new \addons\member\model\TradingRecord();
            $BalanceM = new \addons\member\model\Balance();
            if(isset($sgdOrder['data']['txs'])){
                foreach ($sgdOrder['data']['txs'] as $key => $val) {
                    try{
                        $res = $MemberBtcLog->getDetailByTxid($val['hash']);//订单匹配
                        if($res) continue;
                        if($val['result']<=0) continue;
                        $amount = bcdiv($val['result'], 100000000,8);
                        if($amount>=0.0001){
                            $BalanceM->startTrans();
                            $re_balance = $BalanceM->updateBalance($user_id, $coin_type, $amount,1);
                            if(!$re_balance){
                                $BalanceM->rollback();
                                continue;
                            }
                            $userRecord = $recordM->addRecord($user_id, $amount, $re_balance['before_amount'], $re_balance['amount'], $coin_type, 8, 1, 0, '外网转入');
                            if(!$userRecord){
                                $BalanceM->rollback();
                                continue;
                            }
                            $val['user_id'] = $user_id;
                            $val['amount'] = $amount;
                            $val['sendingaddress'] = $address;
                            if(isset($val['inputs'][0]['prev_out']['addr'])){
                                $val['referenceaddress'] = $val['inputs'][0]['prev_out']['addr'];
                            }
                            $val['block_hash'] = $val['hash'];
                            $val['fee'] = 0;
                            $val['block_time'] = $val['time'];
                            $result = $MemberBtcLog->addLog($val);
                            if(!$result){
                                $BalanceM->rollback();
                                continue;
                            }
                            $BalanceM->commit();
                        }
                    } catch (\Exception $ex) {
                        continue;
                    }
                }
            }
            return true;
        }else{
            return false;
        }
    }


    /**
     * 外网转入记录获取。
     * @return type
     */
    public function getEthOrders($user_id,$eth_address = '',$coin_type=0){
        $cachekey = 'getEthOrders'.$user_id;
        $redis = \think\Cache::connect(\think\Config::get('global_cache'));
        if($redis->get($cachekey)==1){
            return true;
        }
        $redis->set($cachekey,1,3);
        if(!$eth_address) return false;
        if(!$coin_type) return false;
        $eth = new \EthApi();
        $eth->set_byte(18);
        $sgdOrder = $eth->erscan_order($eth_address);
        if(empty($sgdOrder)) return false;
        $MemberEthLog = new \addons\member\model\MemberEthLog();
        $recordM = new \addons\member\model\TradingRecord();
        $BalanceM = new \addons\member\model\Balance();
        foreach($sgdOrder as $val){
            try{
                $res = $MemberEthLog->getDetailByTxid($val['hash']);//订单匹配
                if($res) continue;
                $amount = $val['amount'];
                $stime = date("Y-m-d H:i:s",$val['timeStamp']);
                $BalanceM->startTrans();
                $re_balance = $BalanceM->updateBalance($user_id, $coin_type, $amount,1);
                if(!$re_balance){
                    $BalanceM->rollback();
                    continue;
                }
                $userRecord = $recordM->addRecord($user_id, $amount, $re_balance['before_amount'], $re_balance['amount'], $coin_type, 8, 1, 0, '外网转入');
                if(!$userRecord){
                    $BalanceM->rollback();
                    continue;
                }
                $val['user_id'] = $user_id;
                $res = $MemberEthLog->addLog($val);
                if(!$res){
                    $BalanceM->rollback();
                    continue;
                }
                $BalanceM->commit();
                continue;
            } catch (\Exception $ex) {
                continue;
            }
        }
    }


    /**
     * 外网转入记录获取。
     * @return type
     */
    public function getUsdtOrders($user_id,$eth_address = '',$coin_type=0){
        $cachekey = 'getUsdtOrders'.$user_id;
        $redis = \think\Cache::connect(\think\Config::get('global_cache'));
        if($redis->get($cachekey)==1) return true;
        $redis->set($cachekey,1,3);
        if(!$eth_address) return false;
        if(!$coin_type) return false;
        $eth = new \EthApi();
        $eth->set_byte(6);
        $sgdOrder = $eth->erscan_order($eth_address,1,'to','0xdac17f958d2ee523a2206206994597c13d831ec7');
        if(empty($sgdOrder)) return false;
        $MemberUsdtLog = new \addons\member\model\MemberUsdtLog();
        $recordM = new \addons\member\model\TradingRecord();
        $BalanceM = new \addons\member\model\Balance();
        $userM = new \addons\member\model\MemberAccountModel();
        // $pid_path = $userM->where('id',$user_id)->value('pid_path');
        foreach($sgdOrder as $val){
            try{
                $res = $MemberUsdtLog->getDetailByTxid($val['hash']);//订单匹配
                if($res) continue;
                $amount = $val['amount'];
                $stime = date("Y-m-d H:i:s",$val['timeStamp']);
                $BalanceM->startTrans();
                $re_balance = $BalanceM->updateBalance($user_id, $coin_type, $amount,1);
                if(!$re_balance){
                    $BalanceM->rollback();
                    continue;
                }
                $userRecord = $recordM->addRecord($user_id, $amount, $re_balance['before_amount'], $re_balance['amount'], $coin_type,8, 1, 0, '外网转入');
                if(!$userRecord){
                    $BalanceM->rollback();
                    continue;
                }
                // $res = $userM->where('id',$user_id)->setInc('recharge_total',$amount);
                // if(!$res){
                //     $BalanceM->rollback();
                //     continue;
                // }
                // $res = $userM->where(['id'=>['in',$pid_path.','.$user_id]])->setInc('team_recharge_total',$amount);
                // if(!$res){
                //     $BalanceM->rollback();
                //     continue;
                // }
                $val['user_id'] = $user_id;
                $res = $MemberUsdtLog->addLog($val);
                if(!$res){
                    $BalanceM->rollback();
                    continue;
                }
                $BalanceM->commit();
                continue;
            } catch (\Exception $ex) {
                continue;
            }
        }
        return true;
    }

}

